import type { AxiosResponse } from "axios"
import { ElMessage } from "element-plus"
import JSZip from "jszip"

// 文件夹转zip
export async function filesToZip(files: File[]): Promise<Blob> {
  const zip = new JSZip()
  const promises = files.map(async (file) => {
    const relativePath = file.webkitRelativePath || file.name
    const folderPath = relativePath.split("/").slice(0, -1).join("/")
    const fileName = relativePath.split("/").pop() as string

    const folder = zip.folder(folderPath) || zip

    const fileContent = await file.arrayBuffer()
    folder.file(fileName, fileContent)
  })

  await Promise.all(promises)

  const generatedZip = await zip.generateAsync({
    type: "blob",
    compression: "DEFLATE",
    compressionOptions: {
      level: 9
    }
  })
  return generatedZip
}
// 下载文件
export function downloadFile(res: AxiosResponse) {
  const blob = new Blob([res.data])
  const contentPosition = res.headers["content-disposition"]
  if (contentPosition) {
    const match = contentPosition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
    const fileName = decodeURIComponent(match[1].replace(/['"]/g, ""))
    if ("download" in document.createElement("a")) {
      const elink = document.createElement("a")
      elink.download = fileName
      elink.style.display = "none"
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    }
  } else {
    ElMessage.error("下载失败")
  }
}
